<?php

namespace app\admin\model;

use think\Model;
use think\facade\Db;
use think\File;
use util\File as utilFile;
use util\Http as utilHttp;
use think\facade\Env;

/**
 * 附件模型
 * @package app\admin\model
 */
class Attachment extends Model
{
    // 设置当前模型对应的完整数据表名称
    protected $name = 'admin_attachment';

    // 自动写入时间戳
    protected $autoWriteTimestamp = true;

    /**
     * 根据附件id获取路径
     * @param string|array $id 附件id
     * @param  int $type 类型：0-补全目录，1-直接返回数据库记录的地址
     * @author Rocky
     * @return array|bool|mixed|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getFilePath($id = '', $type = 0)
    {
        if (is_array($id)) {
            $data_list = $this->where('id', 'in', $id)->select();
            $paths = [];
            foreach ($data_list as $key => $value) {
                if ($value['driver'] == 'local') {
                    $paths[$value['id']] = ($type == 0 ? PUBLIC_PATH : '').$value['path'];
                } else {
                    $paths[$value['id']] = $value['path'];
                }
            }
            return $paths;
        } else {
            $data = $this->where('id', $id)->find();
            if ($data) {
                if ($data['driver'] == 'local') {
                    return ($type == 0 ? PUBLIC_PATH : '').$data['path'];
                } else {
                    return $data['path'];
                }
            } else {
                return false;
            }
        }
    }

    /**
     * 根据图片id获取缩略图路径，如果缩略图不存在，则返回原图路径
     * @param string $id 图片id
     * @author Rocky
     * @return array|mixed|string|Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getThumbPath($id = '')
    {
        $result = $this->where('id', $id)->field('path,driver,thumb')->find();
        if ($result) {
            if ($result['driver'] == 'local') {
                return $result['thumb'] != '' ? PUBLIC_PATH.$result['thumb'] : PUBLIC_PATH.$result['path'];
            } else {
                return $result['thumb'] != '' ? $result['thumb'] : $result['path'];
            }
        } else {
            return $result;
        }
    }

    /**
     * 根据图片id获取缩略图路径，如果缩略图不存在，则返回原图路径
     * @param string $id 图片id
     * @author rocky
     * @return array|mixed|string|Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getThumbPaths($ids = '')
    {
        $result = $this->whereIn('id', $ids)->column('id,path,driver,thumb');
        foreach($result as $k=>&$v){
            if ($v) {
                if ($v['driver'] == 'local') {
                    $v['thumb'] != '' ? PUBLIC_PATH.$v['thumb'] : PUBLIC_PATH.$v['path'];
                } else {
                    $v['thumb'] != '' ? $v['thumb'] : $v['path'];
                }
            }
        }
        return $result;
    }

    /**
     * 根据附件id获取名称
     * @param  string $id 附件id
     * @return string     名称
     */
    public function getFileName($id = '')
    {
        return $this->where('id', $id)->value('name');
    }

    static public function getAttachmentExists($where = [], $newTitle = '')
    {
        // 判断附件是否已存在
        $file_exists = self::where('status', 1)->where($where)->find();
        if ($file_exists && $file_exists['path']) {
            $full_path = public_path() . $file_exists['path']; //服务器完整路径
            if (file_exists($full_path) || $file_exists['driver'] != 'local') { //验证本地附件是否存在 || 非本地附件
                if ($newTitle != '' && $newTitle != $file_exists['name']) {
                    self::where('id', $file_exists['id'])->update(['name' => $file_exists['name']=$newTitle]);
                }
                return $file_exists;
            } else {
                self::where('id', $file_exists['id'])->delete(); //清理失效附件
                return self::getAttachmentExists($where, $newTitle);
            }
        } else {
            return null;
        }
    }

    static public function getUrl($driver, $path, $checkExist = true)
    {
        if (!$driver || !$path) {
            return ''; //不存在
        }

        if ($driver == 'local') {
            // 本地服务器文件
            $path = trim($path, '/');
            if ($checkExist) {
                $full_path = public_path() . $path; //服务器完整路径
                if (!file_exists($full_path)) {
                    return ''; //服务器文件不存在
                }
            }
            $file_url = 'https://' . config('app.app_host') . "/"  . $path;
        } else {
            // 非本地驱动（如华为云OBS等），路径已经是完整的URL
            $file_url = $path;
        }
        return $file_url;
    }

    static public function getUrlByid($attachment_id, $islocalFull = false)
    {
        $file_exists = $attachment_id?self::getByid($attachment_id):null;
        if (($file_exists['driver'] ?? '') == 'local' && !$islocalFull) {
            // 本地服务器文件(路径补全)
            $path = trim($file_exists['path'] ?? '', '/');
            return PUBLIC_PATH  . $path;
        }
        return $file_exists ? (self::getUrl($file_exists['driver'] ?? '', $file_exists['path'] ?? '', false)) : '';
    }
}